import { useEffect, useState } from 'react'
import {
  NavBar,
  Icon,
  InputItem,
  WingBlank,
  WhiteSpace,
  Button,
  Toast,
} from 'antd-mobile'
import { Link } from 'react-router-dom'

import { phoneReg, codeReg } from '../../../utils/regs'
import { reqPhoneCode, reqCodeLogin } from '../../../api/login'

import './index.less'

const MAX_TIME = 60
const CLIENT_ID =
  '6e74132885d3147ac2ece210a756aa157981ae000edebb7be50d602f902fac3c'
const REDIRECT_URI = 'http://localhost:5000/login/oauth/gitee'

function CodeLogin({ history, location }) {
  //手机号
  const [phone, setPhone] = useState('')
  //验证码
  const [code, setCode] = useState('')
  //验证码发送倒计时
  const [time, setTime] = useState(0)
  //手机号验证通过则启用登录按钮
  const [isSendDisabled, setIsSendDisabled] = useState(true)
  //验证码验证通过则启用登录按钮
  const [isCodeDisabled, setIsCodeDisabled] = useState(true)
  //是否发送过验证码
  const [isSendCode, setIsSendCode] = useState(false)
  //国家区号
  const countryCode = location.state || '+86'

  //手机号改变触发事件
  const handlePhoneChange = (val) => {
    setPhone(val)
    phoneReg.test(val) ? setIsSendDisabled(false) : setIsSendDisabled(true)
  }

  //验证码改变触发事件
  const handleCodeChange = (val) => {
    setCode(val)
    codeReg.test(val) ? setIsCodeDisabled(false) : setIsCodeDisabled(true)
  }

  //发送请求获取验证码
  const getCode = async () => {
    try {
      setIsSendCode(true)
      setTime(MAX_TIME)
      await reqPhoneCode(phone)
    } catch (err) {
      Toast.fail('请求失败...')
    }
  }

  useEffect(() => {
    //组件挂载或更新完成,当time为0不进行计时
    if (!time) {
      return
    }

    //挂组件挂载或更新完成,修改发送验证码倒计时,time为1时切换按钮
    const timer = setTimeout(() => {
      if (time === 1) {
        setIsSendCode(false)
        return
      }
      setTime(time - 1)
    }, 1000)
    return () => {
      clearTimeout(timer)
    }
  }, [time])

  //发送请求,用验证码登录
  const login = async () => {
    try {
      const res = await reqCodeLogin(phone, code)
      if (res.data.code === 20000) {
        history.push('/', res.data.data)
      } else {
        Toast.fail(res.data.message, 2)
      }
    } catch (err) {
      Toast.fail('请求失败...', 2)
    }
  }

  //用码云gitee进行第三方登录
  const goGitee = () => {
    window.location.href = `https://gitee.com/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code`
  }

  return (
    <div className="login container">
      <NavBar mode="light">硅谷注册登录</NavBar>
      <WhiteSpace size="xl" />
      <WingBlank size="lg">
        <InputItem
          clear
          placeholder="请输入手机号"
          value={phone}
          onChange={handlePhoneChange}
        >
          <Link to="/countryPicker/login" className="login-phone-prefix">
            <span>{countryCode}</span>
            <span>
              <Icon type="down"></Icon>
            </span>
          </Link>
        </InputItem>
        <WhiteSpace size="lg" />
        <div className="login-code">
          <InputItem
            clear
            placeholder="请输入手机验证码"
            value={code}
            onChange={handleCodeChange}
          />
          {isSendCode ? (
            <button
              className="login-btn-text login-btn"
              style={{
                color: '#848689',
              }}
              disabled
            >
              重新获取({time}s)
            </button>
          ) : (
            <button
              className="login-btn-text login-btn"
              style={{
                color: `${isSendDisabled ? '#848689' : 'red'}`,
              }}
              onClick={getCode}
              disabled={isSendDisabled}
            >
              获取验证码
            </button>
          )}
        </div>
        <WhiteSpace size="lg" />
        <WingBlank size="lg">
          <Button
            type="primary"
            className="btn"
            disabled={isSendDisabled || isCodeDisabled}
            onClick={login}
          >
            登录
          </Button>
        </WingBlank>
        <WhiteSpace size="lg" />
        <div className="login-btn-wrap">
          <Link to="/login/password" className="login-btn-text">
            账户密码登录
          </Link>
          <Link to="/register/phone" className="login-btn-text">
            手机快速注册
          </Link>
        </div>
        <div className="login-other-text">其他登录方式</div>
        <div className="login-icons">
          <span
            className="iconfont icon-gitee-fill-round"
            onClick={goGitee}
          ></span>
          <span className="iconfont icon-qq"></span>
          <span className="iconfont icon-wechat"></span>
        </div>
        <span className="login-private-policy">
          未注册的手机号验证后将自动创建硅谷账号, 登录即代表您已同意
          <span className="login-private-policy-btn">硅谷隐私政策</span>
        </span>
      </WingBlank>
    </div>
  )
}

export default CodeLogin
